__author__ = 'jason'

import http.client
import urllib.parse


class ApiKeyError(Exception):
    """
    api key error
    """
    def __init__(self, key_name):
        self.value = key_name

    def __str__(self):
        return 'Tuling API key NOT FOUND, please make sure it was export as "%s" in environment' % (self.value, )

import os
api_key = os.environ.get('TULING_API_KEY')
if not api_key:
    raise ApiKeyError('TULING_API_KEY')


class Query(object):
    # host = 'localhost'
    host = 'www.tuling123.com'

    def __init__(self, info, userid=None, loc=None, lon=None, lat=None):
        self.queried_json = ''
        self.result = {'success': False}

        conn = http.client.HTTPConnection(self.__class__.host)

        url = '/openapi/api'

        url_para = dict()
        url_para['key'] = api_key
        url_para['info'] = info
        if userid:
            url_para['userid'] = userid

        if loc:
            url_para['loc'] = loc
        if lon:
            url_para['lon'] = lon
        if lat:
            url_para['lat'] = lat

        try:
            url_para = urllib.parse.urlencode(url_para)
            conn.request('GET', url+'?'+url_para)

        except Exception as e:
            print(e.args)

        else:
            res = conn.getresponse()
            if res.status == 200:
                self.queried_json = bytes.decode(res.read())

        conn.close()

    def parser(self):
        """
        parser the json GET from tuling123 server
        """

        if self.queried_json:
            import json
            dict_data = json.loads(self.queried_json)
            print(dict_data)

            try:
                code = dict_data['code']

                # 100000	文本类数据
                # 305000	列车
                # 200000	网址类数据
                # 302000	新闻
                # 308000	菜谱、视频、小说
                # 40001	key的长度错误（32位）
                # 40002	请求内容为空
                # 40003	key错误或帐号未激活
                # 40004	当天请求次数已用完
                # 40005	暂不支持该功能
                # 40006	服务器升级中
                # 40007	服务器数据格式异常

                # parse code to type
                if code == 100000:
                    # text
                    self.result['type'] = 'text'

                elif code == 200000:
                    # link
                    self.result['type'] = 'link'
                    self.result['url'] = dict_data['url']

                elif code == 302000:
                    # news
                    self.result['type'] = 'news'
                    self.result['list'] = dict_data['list']

                elif code == 305000:
                    # train
                    self.result['type'] = 'train'
                    self.result['list'] = dict_data['list']

                elif code == 308000:
                    # recipe video novel
                    self.result['type'] = 'recipe'
                    self.result['list'] = dict_data['list']

                else:
                    # error code
                    return

                self.result['text'] = dict_data['text']

            except KeyError:
                return

            self.result['success'] = True

        return self.result

if __name__ == '__main__':
    result = Query(u'你好').parser()
    print(result)
    result = Query(u'新闻').parser()
    print(result)
    result = Query(u'北京到深圳高铁').parser()
    print(result)
    result = Query(u'明天天气').parser()
    print(result)
